package view.listeners;

import java.awt.Color;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;

import model.Constants;
import view.components.IPTextArea;
import controller.Calculator;

public class IpFocusListener extends FocusAdapter {


	private final IPTextArea ipTextArea;

	public IpFocusListener(IPTextArea ipTextArea) {
		this.ipTextArea = ipTextArea;
	}

	@Override
	public void focusLost(FocusEvent e) {

		int ipClass;
		try {
			ipClass = Integer.parseInt(ipTextArea.getTextList().get(0)
					.getText());
		
		int suffix = Calculator.getInstance().calculateIpClass(ipClass);

		switch (suffix) {
		case Constants.CLASS_A:
				editTextFields(1);
			break;
			case Constants.CLASS_B:
				editTextFields(2);
			break;
			case Constants.CLASS_C:
				editTextFields(3);
			break;

		}

		} catch (NumberFormatException e1) {
			for (int i = 1; i < ipTextArea.getTextList().size(); i++) {
				ipTextArea.getTextList().get(i).setEditable(true);
				ipTextArea.getTextList().get(i).setText(Constants.EMPTY);
				ipTextArea.getDotList().get(ipTextArea.getDotList().size() - i)
						.setBackground(Color.white);
			}
		}
	}

	private void editTextFields(int i) {
		for (; i < ipTextArea.getTextList().size(); i++) {
			ipTextArea.getTextList().get(i).setEditable(false);
			ipTextArea.getTextList().get(i).setText(Constants.ZERO);
			ipTextArea.getDotList().get(i - 1)
					.setBackground(ipTextArea.getBackground());
		}
		
	}

}
